package createThread.cn.tedu.threaddemo.test8;

import java.util.concurrent.ArrayBlockingQueue;

class MyBlockingQueue{
    String[] elem = null;
    int head = 0;
    int tail = 0;
    int capacity= 0;

    public MyBlockingQueue() {
        this.elem = new String[100];
    }

    private final Object lock = new Object();
    public void put(String e) throws InterruptedException {

        synchronized (lock){
            while (capacity == elem.length){
                lock.wait();
            }
            elem[tail] = e;
            capacity++;
            tail++;
            if(tail == elem.length){
                tail = 0;
            }
            lock.notify();
        }

    }
    public String take() throws InterruptedException {

        synchronized (lock){
            while (capacity == 0) {
                lock.wait();
            }
            String e = elem[head];
            capacity--;
//            System.out.println("消费的元素为: " + e);
            head++;
            if(head == elem.length){
                head = 0;
            }
            lock.notify();
            return e;
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        System.out.println(myBlockingQueue.capacity);
        System.out.println(myBlockingQueue.elem.length);
        /**
         * 1.生产者线程
         */
        Thread t1 = new Thread(()->{
            int n = 0;
            for (int i = 0; i < 100; i++) {
                try {
                    System.out.println("生产者线程生产的元素: " + n);
                    myBlockingQueue.put(n + "");
                    n++;
//                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        /**
         *2.消费者线程*/
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    String take = myBlockingQueue.take();
                    System.out.println("消费者线程消费的元素: " + take);
//                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
